<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>初验款接收</title>
    <script src="./dist/html2canvas.js"></script>
    <script src="./dist/jspdf.js"></script>
    <script src="./dist/moment.js"></script>
    <style>
        @media print {

            /* 设置横向打印 */
            @page {
                size: A3
                    /* 设置页面方向为横向 */
            }

            /* 设置纵向打印 */
            /* @page {
        size: portrait; // 设置页面方向为纵向
      } */
        }

        body {
            background-color: #fff;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 10px;
        }

        .box {
            padding: 32px;
            /* margin: 62px auto; */
            background: url(./dist/img_01.png) repeat-y;
            background: url(./dist/img_01.png) repeat-y;
            background-position: center top;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
        }

        .title {
            position: relative;
            text-align: center;
            font-size: 20px;
            font-weight: bold;
            padding-bottom: 18px;
            border-bottom: 1px solid #000000;
        }

        .title .logo {
            position: absolute;
            left: 22px;
            bottom: 2px;
            width: 177px;
            height: 75px;
            background: url(./dist/logo.png) center no-repeat;
        }

        .top {
            font-size: 22px;
            margin-bottom: 50px;
        }

        .flex {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        table {
            border-collapse: collapse;
            width: 100%;
            margin-top: 20px;
        }

        th,
        td {
            min-width: 50px;
            border: 1px solid #000;
            padding: 10px 2px 10px 2px;
            font-size: 12px;
            text-align: center;
        }

        td p {
            text-align: start;
            padding-left: 18px;
            margin: 2px 0;
        }

        .bottom {
            position: relative;
            display: flex;
            justify-content: space-around;
            margin-top: 46px;
            font-weight: bold;
            font-size: 12px;
        }

        .bottom .date {
            margin-left: 458px;
        }

        .Approval-info .title {
            text-align: start;
            font-size: 20px;
            border-bottom: 1px solid #e5e5e5;
            padding-bottom: 4px;
            margin-top: 6px;
        }

        ul {
            display: flex;
            flex-wrap: wrap;
            margin: 8px 0 0px 0 !important;
        }

        ul,
        li {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        #dynamicContent {
            display: flex;
            flex-wrap: wrap;
        }

        #dynamicContent li {
            width: 48%;
            margin: 5px;
            margin-bottom: 10px;
            font-size: 12px;
        }

        .Approval-record .title {
            font-size: 12px;
            font-weight: bold;
            padding-bottom: 0;
            border-bottom: 0;
            margin-top: 10px;
            margin-bottom: -12px;
        }

        .Approval-record table th:first-child {
            width: 190px;
        }

        .bottom .zhang {
            position: absolute;
            top: -138px;
            left: 50%;
            margin-left: -15px;
            width: 160px;
            height: 160px;
            background: url(./dist/zhang.png) center no-repeat;
        }

        #exportButton {
            margin: 10px;
            padding: 8px 16px;
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            position: absolute;
            top: 24px;
            right: 24px;
        }

        #exportButton:hover {
            background-color: #0056b3;
        }
    </style>
</head>

<body>
    <div class="box" id="content">
        <div class="title">
            <div class="logo"></div>（上市）订购接收与到货验收单 <span
                style="font-size: 12px;font-weight: normal;">APO304689210500248</span>
        </div>
        <div id="dynamicContent">
            <!-- Dynamic content will be rendered here -->
        </div>
        <div id="table-container"></div>
        <div class="Approval-record" id="Approval-record">
        </div>
        <div class="bottom flex">
            <span class="buyer">采购员：<span></span></span>
            <span>收货方盖章</span>
            <span>供应商盖章</span>
        </div>
        <div class="bottom">
            <div class="date"></div>
            <div class="zhang"></div>
        </div>
    </div>
    <button id="exportButton">导出</button>
    <script>
        // 获取要导出的HTML元素
        const element = document.getElementById('content')

        exportButton.addEventListener('click', () => {
            document.getElementById("exportButton").hidden = true
            window.document.title = `初款接收单`
            window.print()
            document.getElementById("exportButton").hidden = false
            window.document.title = `初验款接收`
        })
    </script>
    <script>
        var info = {
            buyer: "戴宣鸿", // 采购员
            date: '2021-05-31' // 底部日期
        }

        // 用于动态填充用户信息的函数
        function fillUserInfo() {
            document.querySelector('.buyer span').innerText = info.buyer
            document.querySelector('.bottom .date').innerText = info.date

        }
        // 上面表格数据
        var dataArray = [
            { title: '订单编号', dataIndex: 'orderNo', value: 'APO304689210500248' },
            { title: 'ERP订单编号', dataIndex: 'erpOrderNo', value: 'APO304689210500248' },
            { title: '供应商名称', dataIndex: 'supplierName', value: '云南北极光数码科技有限公司' },
            { title: '资金来源', dataIndex: 'capitalSource', value: '资本' },
            { title: '物资类型', dataIndex: 'materialType', value: '工程物资' },
            { title: '需求单位', dataIndex: 'demandUnit', value: '昆明分公司' },
            { title: '合同编号', dataIndex: 'contractNo', value: 'KM工建20190936' },
            { title: '合同名称', dataIndex: 'contractName', value: '中国移动云南公司昆明分公司2019-2020年社区、无线深度覆盖施工安装项目框架\n合同（标段一 云南北极光）' },
            { title: '订单主体', dataIndex: 'orderSubject', value: '昆明分公司' },
            { title: '采购部门', dataIndex: 'procurementDepartment', value: '云南公司\\昆明分公司\\工程建设中心\\传输组' },
            { title: '未税金额(元)', dataIndex: 'untaxedAmount', value: '28,879.30' },
            { title: '税金(元)', dataIndex: 'taxAmount', value: '2,599.15' },
            { title: '含税金额(元)', dataIndex: 'taxIncludedAmount', value: '31,478.45' },
            { title: '含税金额(大写)', dataIndex: 'taxIncludedAmountInWords', value: '叁万壹仟肆佰柒拾捌圆肆角伍分' }
        ]
        function renderData(dataArray) {
            var dynamicContent = document.getElementById('dynamicContent')
            var html = '<ul>'
            dataArray.forEach(function (item) {
                html += '<li><strong>' + item.title + ':</strong> ' + item.value + '</li>'
            })
            html += '</ul>'
            dynamicContent.innerHTML = html
        }

        function fillPaymentTable(tableName, data, headers, isNeedTotal) {
            // 模拟数据
            var data = data

            // 获取表格容器
            var tableContainer = document.getElementById(tableName)

            // 创建表格元素
            var table = document.createElement('table')
            table.setAttribute('border', '1')

            // 创建表头
            var thead = document.createElement('thead')
            var headerRow = document.createElement('tr')
            var headers = headers

            for (var i = 0; i < headers.length; i++) {
                var th = document.createElement('th')
                th.appendChild(document.createTextNode(headers[i]))
                headerRow.appendChild(th)
            }

            thead.appendChild(headerRow)
            table.appendChild(thead)

            if (data.length === 0) {
                // 数据为空时显示无记录消息
                var noRecordRow = document.createElement('tr')
                var noRecordCell = document.createElement('td')
                noRecordCell.setAttribute('colspan', headers.length)
                noRecordCell.appendChild(document.createTextNode('无记录!'))
                noRecordRow.appendChild(noRecordCell)

                var tbody = document.createElement('tbody')
                tbody.appendChild(noRecordRow)
                table.appendChild(tbody)
            } else {
                // 创建表格内容
                var tbody = document.createElement('tbody')

                for (var i = 0; i < data.length; i++) {
                    var row = document.createElement('tr')

                    for (var key in data[i]) {
                        var cell = document.createElement('td')
                        cell.appendChild(document.createTextNode(data[i][key]))
                        row.appendChild(cell)
                    }

                    tbody.appendChild(row)
                }

                if (isNeedTotal) {
                    // 添加合计行
                    var totalRow = document.createElement('tr')
                    var emptyColumns = Object.keys(data[0]).map(function () { return '' })

                    // 设置“合计”文本
                    emptyColumns[0] = '合计'

                    // 计算“不含税总价”和“含税总价”列的合计
                    var totalPriceExclTaxSum = data.reduce(function (sum, item) {
                        return sum + parseFloat(item.total_price_excl_tax || 0)
                    }, 0)
                    emptyColumns[10] = totalPriceExclTaxSum.toFixed(2)

                    var totalPriceInclTaxSum = data.reduce(function (sum, item) {
                        return sum + parseFloat(item.total_price_incl_tax || 0)
                    }, 0)
                    emptyColumns[14] = totalPriceInclTaxSum.toFixed(2)

                    // 创建合计行
                    emptyColumns.forEach(function (value) {
                        var cell = document.createElement('td')
                        cell.appendChild(document.createTextNode(value))
                        totalRow.appendChild(cell)
                    })

                    tbody.appendChild(totalRow)
                }

                table.appendChild(tbody)
            }

            // 将表格添加到容器中
            tableContainer.appendChild(table)
        }
        let data = [
            { id: "1", projectCode: "C20304689000018", projectName: '中国移动云南公司昆明分公司2020年第十四批数字家庭项目', materialCode: "10416480", materialDescription: "传输管线施工(二采)\社区、集客、无线深度覆盖", unit: "项", orderQuantity: "6680.18", untaxedUnitPrice: "1", isDeductible: "是", taxRate: "9%", untaxedAmount: "6680.18", inventoryOrg: "IO_E_YN_304689_昆明分公司", receivedQuantity: "6680.18", actualArrivalTime: "2021-05-31", receiver: "董俊", orderReceiver: "1" }
        ]
        let headers = ["行号", "工程项目编码", "工程项目名称", "物料编码", "物料描述", "单位", "订单数量", "未税单价（元）", "是否可抵扣", "税率", "未税金额", "库存组织", "签收数量", "实际到货时间", "接收人", "订单接收人（料账员）"]
        let recordData = [
            { id: "1", addressName: "无" }
        ]
        let recordHeaders = ["行号", "收货地址"]
        window.onload = function () {
            var queryString = window.location.search
            var urlParams = new URLSearchParams(queryString)
            var id = urlParams.get('id')
            fetch('http://api.ynjov.com:8080/api/getPurchaseOrderDetail/' + id)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok')
                    }
                    return response.json()
                })
                .then(({ data: res, items, infos }) => {
                    // info = data
                    const dtArr = dataArray.map((item) => {
                        item.value = res[item.dataIndex]
                        return item
                    })
                    data = items.map((item, index) => {
                        delete item.id
                        delete item.createdAt
                        delete item.updatedAt
                        delete item.purchaseOrderId
                        item.taxRate = item.taxRate.indexOf('%') > -1 ? item.taxRate : (item.taxRate + '%')
                        item.orderReceiver = item.orderReceiver ? item.orderReceiver : ''
                        return {
                            id: index + 1,
                            ...item,
                            actualArrivalTime: '      ' + moment(item.actualArrivalTime).format('YYYY-MM-DD') + '     '
                        }
                    })
                    recordData = infos.map((item, index) => {
                        delete item.id
                        delete item.createdAt
                        delete item.updatedAt
                        delete item.purchaseOrderId
                        return {
                            index: index + 1,
                            ...item,
                        }
                    })
                    renderData(dtArr)
                    fillUserInfo()
                    fillPaymentTable('table-container', data, headers)
                    fillPaymentTable('Approval-record', recordData, recordHeaders)
                })
                .catch(error => {
                    console.error('Fetch error:', error)
                })
        };
    </script>
</body>

</html>